import json
from socket import *
from select import *
from settings import *
class Application:
    def __init__(self):
        self.server=socket()
        self.server.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
        self.server.bind((frame_ip,frame_port))
        self.server.listen(5)
        self.r_list,self.w_list,self.x_list =[self.server],[],[]


    def start(self):
        while True:
            r,w,x=select(self.r_list,self.w_list,self.x_list)
            for item in  r:
                if item is self.server:
                    conn,addr = item.accept()
                    print("connected from",addr)
                    self.r_list.append(conn)
                else:
                    data=item.recv(2048).decode()
                    if not data:
                        self.r_list.remove(item)
                        item.close()
                        continue
                    self.response(item,data)
                    self.r_list.remove(item)


    def response(self,coon,data):
        recv_origin_data = json.loads(data)
        if recv_origin_data['method']=='GET':
            if recv_origin_data['path'] == "/" or recv_origin_data['path'][-5:] == ".html":
                to_send=self.get_html(recv_origin_data["path"])
                coon.send(json.dumps(to_send).encode())

            else:
                to_send={"status":404,"data":"NOT FOUND"}
                coon.send(json.dumps(to_send).encode())

        elif recv_origin_data['method']=="POST":
            pass


    def get_html(self,filename):
        if filename=="/":
            with open("index.html","rb") as f:
                data=f.read()
                return {"status":200, "data":data.decode()}
        file_path=os.path.join(base_path,filename[1:])
        print(file_path)
        try:
            with open(file_path,"rb") as f:
                data=f.read()
                return {"status":200, "data":data.decode()}
        except Exception as e:
            print(e)
            with open("404.html","rb") as f:
                return {"status": 404, "data":f.read().decode()}



if __name__ == '__main__':
    application=Application()
    result=application.get_html("\Body.html")
    second=json.dumps(result).encode()
    print(len(second))
    print(json.loads(second.decode()))




